<template>
  <div style="width: 100%; height: 100%;">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2
          v-model:expanded-row-keys="expandedRowKeys"
          v-loading="tableLoading"
          :columns="columns"
          :data="treeData"
          :width="width"
          :height="height"
          :row-key="'id'"
          :expand-column-key="'label'"
          :fixed="true"
          :default-expanded-row-keys="['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']"
          @row-expand="onRowExpanded"
          @expanded-rows-change="onExpandedRowsChange"
        />
      </template>
    </el-auto-resizer>

    <el-dialog v-model="showUpdate" title="修改" width="460px" append-to-body destroy-on-close >
      <el-form ref="updateForm" :model="formData" :rules="rules" label-width="80px" style="margin-top: 20px">
        <el-form-item v-if="formData.parentId != 0" label="父级" prop="id">
          <el-select v-model="formData.parentId" placeholder="请选择" style="width: 300px" >
            <el-option v-for="item in treeData" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="id" prop="equipmentTypeId">
          <el-input v-model="formData.equipmentTypeId" maxlength="20" show-word-limit clearable placeholder="请输入id" style="width: 300px;" @input="(value)=> { formData.id = formatIntNumber(value) }" />
        </el-form-item>
        <el-form-item label="名称" prop="equipmentTypeName">
          <el-input v-model="formData.equipmentTypeName" style="width: 300px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div >
          <el-button @click="showUpdate = false">取消</el-button>
          <el-button :loading="buttonLoading" :disabled="buttonLoading" type="primary" @click="submitUpdate">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showAdd" title="新增" width="460px" append-to-body destroy-on-close >
      <el-form ref="addForm" :model="formData" :rules="rules" label-width="80px" style="margin-top: 20px">
        <el-form-item label="id" prop="equipmentTypeId">
          <el-input v-model="formData.equipmentTypeId" maxlength="20" show-word-limit clearable placeholder="请输入id" style="width: 300px" @input="(value)=> { formData.id = formatIntNumber(value) }" />
        </el-form-item>
        <el-form-item label="名称" prop="equipmentTypeName">
          <el-input v-model="formData.equipmentTypeName" style="width: 300px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div >
          <el-button @click="showAdd = false">取消</el-button>
          <el-button :loading="buttonLoading" :disabled="buttonLoading" type="primary" @click="submitAdd">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { TableV2FixedDir } from 'element-plus'
import request from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { formatIntNumber } from '@/utils/numberUtil';

import type { ExpandedRowsChangeHandler, RowExpandHandler } from 'element-plus'
const treeList = ref();
const addForm = ref();
const updateForm = ref();
const buttonLoading = ref(false);
const showUpdate = ref(false);
const showAdd = ref(false);
const formData = ref<any>({
  equipmentTypeName: '',
  equipmentTypeId: ''
});
const rules = {
  equipmentTypeName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  equipmentTypeId: [
    { required: true, message: '请输入id', trigger: 'blur' }
  ]
};

/** 查询设备类型树列表 */
const tableLoading = ref(false);
const expandedRowKeys = ref<any>([]);
const getEquipmentTypeList = async () => {
  tableLoading.value = true
  const res = await request({ url: '/equipment/equipment-type/treeList', method: 'get' }).finally(() => tableLoading.value = false);
  console.log('查询设备类型树列表', res);

  treeList.value = res.data.map((item:any) => ({
    id: item.id,
    label: item.label,
    parentId: item.parentId,
    children: item.children?.map((child:any) => ({
      id: child.id,
      label: child.label,
      parentId: child.parentId
    }))
  }));
};

const treeData = computed(() => treeList.value || []);

// 添加按钮
const handleAdd = (row: any) => {
  reset();
  showAdd.value = true;

  // 显示父级名称
  formData.value.parentId = row.rowData.id
};

// 修改按钮
const handleEdit = (row:any) => {
  showUpdate.value = true;
  formData.value = { equipmentTypeName: row.rowData.label, equipmentTypeId: row.rowData.id, parentId: row.rowData.parentId };
};

const columns:any = [
  { key: 'label', dataKey: 'label', title: '名称', width: 300, fixed: TableV2FixedDir.LEFT },
  { key: 'id', dataKey: 'id', title: 'id', align: 'center', width: 300 },
  { key: 'parentId', dataKey: 'parentId', title: 'parentId', align: 'center', width: 300 },
  {
    key: 'action',
    title: '操作',
    align: 'center',
    width: 200,
    fixed: TableV2FixedDir.RIGHT,
    cellRenderer: (row: any) => {
      if (row.rowData.parentId != 0) {
        // 如果有子节点,则不渲染"添加"按钮
        return h(
          'el-button',
          {
            type: 'primary',
            size: 'small',
            onClick: () => handleEdit(row),
            style: { color: '#409eff', cursor: 'pointer', margin: '0 10px' }
          },
          { default: () => '修改' }
        );
      } else {
        return h('div', [
          h(
            'el-button',
            {
              type: 'primary',
              size: 'small',
              onClick: () => handleAdd(row),
              style: { color: '#409eff', cursor: 'pointer', margin: '0 10px' }
            },
            { default: () => '添加' }
          ),
          h(
            'el-button',
            {
              type: 'primary',
              size: 'small',
              onClick: () => handleEdit(row),
              style: { color: '#409eff', cursor: 'pointer' }
            },
            { default: () => '修改' }
          )
        ]);
      }
    }
  }
];

const onRowExpanded = ({ expanded }: Parameters<RowExpandHandler>[0]) => {
  console.log('点击箭头图标展开/折叠：', expanded);
};

const onExpandedRowsChange = (expandedKeys: Parameters<ExpandedRowsChangeHandler>[0]) => {
  console.log('行展开状态改变时触发：', expandedKeys);
};

/** 表单重置 */
const reset = () => {
  formData.value = { name: '', id: '' };
  addForm.value?.resetFields();
  updateForm.value?.resetFields();
}

/** 新增提交按钮 */
const submitAdd = () => {
  addForm.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      await request({ url: '/equipment/equipment-type', method: 'post', data: { parentId: 0, ...formData.value }}).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');

      showAdd.value = false;
      reset();
      getEquipmentTypeList();
    }
  });
}
/** 修改提交按钮 */
const submitUpdate = () => {
  updateForm.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      await request({ url: '/equipment/equipment-type', method: 'put', data: formData.value }).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');

      showUpdate.value = false;
      reset();
      getEquipmentTypeList();
    }
  });
}

onMounted(() => {
  getEquipmentTypeList();
});
</script>

<style scoped lang="scss">
:deep(.el-table-v2__empty) {
  display: none;
}
</style>
